<!DOCTYPE html>
<html>
<head>
    <title>玉石产品录入</title>
    <link rel="stylesheet" href="../static/css/ej.css">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">

    <style>
        .product-form {
            max-width: 1000px;
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #333;
        }
        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .form-group textarea {
            height: 80px;
            resize: vertical;
        }
        .form-row {
            display: flex;
            gap: 15px;
            margin-bottom: 15px;
        }
        .form-row .form-group {
            flex: 1;
            margin-bottom: 0;
        }
        .required::after {
            content: " *";
            color: #d32f2f;
        }
        .submit-btn {
            background-color: #c0a36c;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 20px;
        }
        .submit-btn:hover {
            background-color: #a88c5a;
        }
        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }
        .error {
            color: #d32f2f;
            padding: 10px;
            background-color: #ffebee;
            border-radius: 4px;
            margin: 10px 0;
        }
        .success {
            color: #2e7d32;
            padding: 10px;
            background-color: #e8f5e8;
            border-radius: 4px;
            margin: 10px 0;
        }
    </style>
</head>
<body style="background-color:#fffbf6">
    
    <!-- 状态栏 -->
    {% include 'status_bar.html' %}
    
    <!-- 返回主菜单按钮 -->
    <div style="max-width: 1000px; margin: 20px auto 10px auto; padding: 0 20px;">
        <a href="/ej_index" class="btn btn-outline-secondary btn-sm" style="margin-bottom: 10px;">
            <i class="bi bi-arrow-left"></i> 返回主菜单
        </a>
    </div>
    
    <h2 style="max-width: 1000px; margin: 0 auto 20px auto; padding: 0 20px;">玉石产品录入</h2>

    <div id="loading" class="loading">正在加载配置信息...</div>
    <div id="error" class="error" style="display: none;"></div>
    <div id="success" class="success" style="display: none;"></div>

    <form id="productForm" class="product-form" style="display: none;">
        <!-- 基本信息 -->
        <div class="form-row">
            <div class="form-group">
                <label class="required">产品ID</label>
                <input type="text" id="product_id" name="product_id" required>
            </div>
            <div class="form-group">
                <label class="required">产品名称</label>
                <input type="text" id="product_name" name="product_name" required>
            </div>
        </div>

        <!-- 类型选择 -->
        <div class="form-row">
            <div class="form-group">
                <label class="required">一级类型</label>
                <select id="type_1" name="type_1" required onchange="updateType2Options()">
                    <option value="">请选择</option>
                </select>
            </div>
            <div class="form-group">
                <label class="required">二级类型</label>
                <select id="type_2" name="type_2" required>
                    <option value="">请先选择一级类型</option>
                </select>
            </div>
        </div>

        <!-- 五行和颜色 -->
        <div class="form-row">
            <div class="form-group">
                <label class="required">五行属性</label>
                <input type="text" id="wu_xings" name="wu_xings" placeholder="如：木,火" required>
            </div>
            <div class="form-group">
                <label class="required">颜色</label>
                <input type="text" id="colors" name="colors" placeholder="如：红,绿" required>
            </div>
        </div>

        <!-- 材质信息 -->
        <div class="form-row">
            <div class="form-group">
                <label class="required">主要材质</label>
                <input type="text" id="major_material" name="major_material" required>
            </div>
            <div class="form-group">
                <label>次要材质</label>
                <input type="text" id="second_material" name="second_material">
            </div>
        </div>

        <div class="form-row">
            <div class="form-group">
                <label>第三材质</label>
                <input type="text" id="third_material" name="third_material">
            </div>
            <div class="form-group">
                <label>配件材质</label>
                <input type="text" id="accessories_material" name="accessories_material">
            </div>
        </div>

        <!-- 尺寸信息 -->
        <div class="form-row">
            <div class="form-group">
                <label class="required">主要直径 (mm)</label>
                <input type="number" step="0.01" id="major_diameter" name="major_diameter" required>
            </div>
            <div class="form-group">
                <label>次要直径 (mm)</label>
                <input type="number" step="0.01" id="second_diameter" name="second_diameter">
            </div>
        </div>

        <div class="form-row">
            <div class="form-group">
                <label>第三直径 (mm)</label>
                <input type="number" step="0.01" id="third_diameter" name="third_diameter">
            </div>
            <div class="form-group">
                <label class="required">总长度 (cm)</label>
                <input type="number" step="0.01" id="total_length" name="total_length" required>
            </div>
        </div>

        <!-- 调整选项 -->
        <div class="form-row">
            <div class="form-group">
                <label>可调节长度</label>
                <select id="adjust_length" name="adjust_length">
                    <option value="no">否</option>
                    <option value="yes">是</option>
                </select>
            </div>
            <div class="form-group">
                <label>可调节形状</label>
                <select id="adjust_shape" name="adjust_shape">
                    <option value="no">否</option>
                    <option value="yes">是</option>
                </select>
            </div>
        </div>

        <!-- 设计师信息 -->
        <div class="form-row">
            <div class="form-group">
                <label class="required">设计师</label>
                <select id="designer_id" name="designer_id" required>
                    <option value="">请选择</option>
                </select>
            </div>
        </div>

        <div class="form-row">
            <div class="form-group">
                <label class="required">设计日期</label>
                <input type="date" id="designed_date" name="designed_date" required>
            </div>
        </div>

        <!-- 备注 -->
        <div class="form-group">
            <label>备注</label>
            <textarea id="comment" name="comment" placeholder="请输入备注信息"></textarea>
        </div>

        <!-- 封面图片上传 -->
        <div class="form-group">
            <label>封面图片</label>
            <div style="display: flex; gap: 10px; align-items: center;">
                <button type="button" id="uploadCoverBtn" class="submit-btn" style="padding: 8px 16px; margin: 0;">
                    上传封面图
                </button>
                <span id="coverStatus" style="color: #666;">未上传</span>
            </div>
            <input type="file" id="coverImage" accept=".jpg,.jpeg,.png" style="display: none;">
        </div>

        <button type="submit" class="submit-btn">提交产品信息</button>
    </form>

    <script src="../static/js/common.js"></script>
    <script>
        let configData = null;

        // 页面加载时获取配置信息
        document.addEventListener('DOMContentLoaded', function() {
            loadConfig();
        });

        // 加载配置信息
        function loadConfig() {
            const loading = document.getElementById('loading');
            const error = document.getElementById('error');
            
            loading.style.display = 'block';
            error.style.display = 'none';

            fetch('/get_ejj_jade_json_config')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('无法获取配置信息');
                    }
                    return response.json();
                })
                .then(data => {
                    loading.style.display = 'none';
                    configData = data.config;
                    console.log('配置数据:', configData);
                    console.log('类型数据:', configData.types);
                    initForm();
                })
                .catch(error => {
                    loading.style.display = 'none';
                    error.style.display = 'block';
                    error.textContent = '加载配置失败: ' + error.message;
                });
        }

        // 初始化表单
        function initForm() {
            const form = document.getElementById('productForm');
            form.style.display = 'block';

            // 初始化类型选项
            initTypeOptions();
            
            // 初始化设计师选项
            initDesignerOptions();

            // 设置当前日期为默认设计日期
            document.getElementById('designed_date').value = new Date().toISOString().split('T')[0];
            
            // 设计师选择事件不再需要，因为设计师姓名字段已删除
            
            // 设置二级类型改变事件
            document.getElementById('type_2').addEventListener('change', updateProductIdOnTypeChange);
            
            // 设置产品ID为只读
            document.getElementById('product_id').readOnly = true;
        }

        // 初始化类型选项
        function initTypeOptions() {
            const type1Select = document.getElementById('type_1');
            type1Select.innerHTML = '<option value="">请选择</option>';
            
            if (configData && configData.types) {
                for (const [typeName, subTypes] of Object.entries(configData.types)) {
                    const option = document.createElement('option');
                    option.value = typeName;
                    option.textContent = typeName;
                    type1Select.appendChild(option);
                }
            }
        }

        // 更新二级类型选项
        function updateType2Options() {
            const type1 = document.getElementById('type_1').value;
            const type2Select = document.getElementById('type_2');
            
            type2Select.innerHTML = '<option value="">请选择</option>';
            
            if (type1 && configData && configData.types && configData.types[type1]) {
                configData.types[type1].forEach(subType => {
                    const option = document.createElement('option');
                    option.value = subType.name;
                    option.textContent = subType.name;
                    option.dataset.code = subType.code;
                    type2Select.appendChild(option);
                });
            }
            
            // 重置产品ID
            generateProductId();
        }
        
        // 二级类型改变时更新产品ID
        function updateProductIdOnTypeChange() {
            generateProductId();
        }
        
        // 生成产品ID
        function generateProductId() {
            const type1 = document.getElementById('type_1').value;
            const type2Select = document.getElementById('type_2');
            const productIdInput = document.getElementById('product_id');
            
            if (type1 && type2Select.value) {
                const selectedOption = type2Select.options[type2Select.selectedIndex];
                const typeCode = selectedOption.dataset.code;
                
                if (typeCode) {
                    // 生成时间戳（精确到秒）
                    const now = new Date();
                    const timestamp = now.toISOString().replace(/[-:]/g, '').replace('T', '').split('.')[0].substring(2, 14);
                    
                    // 生成产品ID: EJ + 类型代码 + 时间戳
                    const productId = `EJ-${typeCode}-${timestamp}`;
                    productIdInput.value = productId;
                }
            } else {
                productIdInput.value = '';
            }
        }

        // 初始化设计师选项
        function initDesignerOptions() {
            const designerSelect = document.getElementById('designer_id');
            designerSelect.innerHTML = '<option value="">请选择</option>';
            
            if (configData && configData.designer) {
                configData.designer.forEach(designer => {
                    const option = document.createElement('option');
                    // 显示格式为 "DE001-水母"
                    option.value = `${designer.id}-${designer.name}`;
                    option.textContent = `${designer.id}-${designer.name}`;
                    option.dataset.id = designer.id;
                    option.dataset.name = designer.name;
                    designerSelect.appendChild(option);
                });
            }
        }

        // 更新设计师姓名（不再需要，因为设计师姓名字段已删除）
        function updateDesignerName() {
            // 此函数不再需要，因为设计师姓名字段已删除
        }

        // 表单提交处理
        document.getElementById('productForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const data = Object.fromEntries(formData.entries());
            
            // 处理设计师信息：将"DE001-水母"格式拆分为designer_id和designer_name
            const designerValue = data.designer_id;
            if (designerValue && designerValue.includes('-')) {
                const [designerId, designerName] = designerValue.split('-');
                data.designer_id = designerId;
                data.designer_name = designerName;
            }
            
            // 添加时间戳
            data.created_at = new Date().toISOString();
            data.updated_at = new Date().toISOString();
            
            // 发送数据到后端
            submitProductData(data);
        });

        // 提交产品数据
        function submitProductData(data) {
            const submitBtn = document.querySelector('button[type="submit"]');
            const uploadCoverBtn = document.getElementById('uploadCoverBtn');
            const error = document.getElementById('error');
            const success = document.getElementById('success');
            
            submitBtn.disabled = true;
            submitBtn.textContent = '提交中...';
            error.style.display = 'none';
            success.style.display = 'none';

            fetch('/save_jade_product', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('保存失败');
                }
                return response.json();
            })
            .then(result => {
                if (result.res === 'ok') {
                    success.style.display = 'block';
                    success.textContent = '产品信息保存成功！';
                    
                    // 如果产品保存成功且已选择封面图片，则上传封面图片
                    const coverImage = document.getElementById('coverImage');
                    if (coverImage.files.length > 0) {
                        uploadCoverImage(result.product_id);
                    } else {
                        document.getElementById('productForm').reset();
                        document.getElementById('coverStatus').textContent = '未上传';
                    }
                } else {
                    throw new Error(result.message || '保存失败');
                }
            })
            .catch(error => {
                error.style.display = 'block';
                error.textContent = '保存失败: ' + error.message;
            })
            .finally(() => {
                submitBtn.disabled = false;
                submitBtn.textContent = '提交产品信息';
                // 确保上传封面图按钮文字保持不变
                uploadCoverBtn.textContent = '上传封面图';
            });
        }

        // 初始化封面图片上传功能
        function initCoverUpload() {
            const uploadBtn = document.getElementById('uploadCoverBtn');
            const coverImage = document.getElementById('coverImage');
            const coverStatus = document.getElementById('coverStatus');

            // 点击上传按钮触发文件选择
            uploadBtn.addEventListener('click', function() {
                coverImage.click();
            });

            // 文件选择变化时处理
            coverImage.addEventListener('change', function(e) {
                if (e.target.files.length > 0) {
                    const file = e.target.files[0];
                    const fileName = file.name.toLowerCase();
                    
                    // 检查文件类型
                    if (!fileName.endsWith('.jpg') && !fileName.endsWith('.jpeg') && !fileName.endsWith('.png')) {
                        alert('请选择jpg、jpeg或png格式的图片文件');
                        e.target.value = '';
                        coverStatus.textContent = '未上传';
                        return;
                    }
                    
                    // 检查文件大小（限制为5MB）
                    if (file.size > 5 * 1024 * 1024) {
                        alert('图片文件大小不能超过5MB');
                        e.target.value = '';
                        coverStatus.textContent = '未上传';
                        return;
                    }
                    
                    coverStatus.textContent = `已选择: ${file.name}`;
                } else {
                    coverStatus.textContent = '未上传';
                }
            });
        }

        // 上传封面图片
        function uploadCoverImage(productId) {
            const coverImage = document.getElementById('coverImage');
            const coverStatus = document.getElementById('coverStatus');
            const uploadCoverBtn = document.getElementById('uploadCoverBtn');
            const error = document.getElementById('error');
            const success = document.getElementById('success');
            
            if (coverImage.files.length === 0) {
                return;
            }

            const file = coverImage.files[0];
            const formData = new FormData();
            formData.append('cover_image', file);
            formData.append('product_id', productId);

            coverStatus.textContent = '上传中...';

            fetch('/deal_jade_cover_img', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('封面图片上传失败');
                }
                return response.json();
            })
            .then(result => {
                if (result.res === 'ok') {
                    coverStatus.textContent = '上传成功';
                    success.textContent += ' 封面图片上传成功！';
                    
                    // 重置表单
                    document.getElementById('productForm').reset();
                    document.getElementById('coverStatus').textContent = '未上传';
                } else {
                    throw new Error(result.message || '封面图片上传失败');
                }
            })
            .catch(error => {
                coverStatus.textContent = '上传失败';
                error.style.display = 'block';
                error.textContent = '封面图片上传失败: ' + error.message;
            })
            .finally(() => {
                // 确保上传封面图按钮文字保持不变
                uploadCoverBtn.textContent = '上传封面图';
            });
        }

        // 在初始化表单时调用封面上传初始化
        function initForm() {
            const form = document.getElementById('productForm');
            form.style.display = 'block';

            // 初始化类型选项
            initTypeOptions();
            
            // 初始化设计师选项
            initDesignerOptions();

            // 初始化封面上传功能
            initCoverUpload();

            // 设置当前日期为默认设计日期
            document.getElementById('designed_date').value = new Date().toISOString().split('T')[0];
            
            // 设置二级类型改变事件
            document.getElementById('type_2').addEventListener('change', updateProductIdOnTypeChange);
            
            // 设置产品ID为只读
            document.getElementById('product_id').readOnly = true;
        }
    </script>
</body>
</html>
